<template>
  <div class="app-container">
    <el-dialog
      title="授权"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false">
      <el-tree
        :data="data"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
        :props="defaultProps"
        :check-strictly="true">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveHandler">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import adminRoleApi from '@/api/core/sys/admin-role'
  export default {
    data () {
      return {
        dialogVisible: false,
        data: [],
        defaultProps: {
          children: 'children',
          label: 'menuTitle'
        },
        dataForm: {
          id: '',
          roleId: '',
          menuIds: []
        }
      }
    },
    created() {},
    methods: {
      init(id) {
        this.dialogVisible = true
        this.dataForm.roleId = id
        adminRoleApi.listMenus().then(res => {
          this.data= res.data.menus
        }).catch(res => {
          this.$message.error(res.message)
        })
        // 通过角色查询所属菜单
        this.getRoleMenus()
      },
      // 通过角色查询所属菜单
      getRoleMenus() {
        adminRoleApi.listByRoleId(this.dataForm.roleId).then(res => {
          this.$refs.tree.setCheckedKeys(res.data.menuIds)
        })
      },
      // 确定
      saveHandler() {
        this.dataForm.menuIds = this.$refs.tree.getCheckedKeys()
        this.$confirm('确定修改吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          adminRoleApi.saveOrUpdateMenus(this.dataForm).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.dialogVisible = false
            this.$emit('refreshDataList')
          }).catch(res => {
            this.$message.error(res.message)
          })          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        })
      }
    }
  }
</script>

<style scoped></style>